import pyaudio
import wave
import numpy as np

"""
CHUNK：块的大小，即每次读取的大小，一般设置为1024
FORMAT：音频的格式，一般设置为paInt16
CHANNELS：声道，一般设置为1
RATE：采样率，一般设置为44100
RECORD_SECONDS：录音时间，一般设置为10
"""

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 15
AMPLIFICATION_FACTOR = 10  # 放大因子，可以根据需要调整 

def record_audio(file_name):
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    
    # print("开始录音，请说话...")
    frames = []
    
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    
    # print("录音结束，正在保存文件...")
    stream.stop_stream()
    stream.close()
    p.terminate()
    
    # 将音频数据转换为numpy数组进行放大处理  
    audio_data = np.frombuffer(b''.join(frames), dtype=np.int16)  
    amplified_data = np.int16(audio_data * AMPLIFICATION_FACTOR)  
      
    # 防止数据溢出  
    np.clip(amplified_data, -32768, 32767, out=amplified_data)  

        # 保存放大后的音频数据到文件  
    wf = wave.open(file_name, 'wb')  
    wf.setnchannels(CHANNELS)  
    wf.setsampwidth(p.get_sample_size(FORMAT))  
    wf.setframerate(RATE)  
    wf.writeframes(amplified_data.tobytes())  
    wf.close()  

# record_audio("test.mp3")